﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using AstekServis.Web.Data;

namespace AstekServis.Views
{
    public partial class SozlesmeTanitim : ChildWindow
    {
        public enum FormTipleri
        {
            FilmSozlesmesi,
            GarantiSozlesmesi
        }

        public AracBilgi SecilenArac { get; set; }
        public FormTipleri FormTipi { get; set; }
        AsTekDomainContext context = new AsTekDomainContext();
        public int SelectedID { get; set; }
        List<Arac> AracListesi = new List<Arac>();
        List<Film> FilmListesi = new List<Film>();

        public SozlesmeTanitim()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(SozlesmeTanitim_Loaded);
            agDataGrid1.RowClick += new DevExpress.AgDataGrid.RowClickEventHandler(agDataGrid1_RowClick);
        }

        void agDataGrid1_RowClick(object sender, DevExpress.AgDataGrid.RowClickEventArgs e)
        {
            if (agDataGrid1.FocusedRowHandle > -1)
            {
                Sozlesme sz = (Sozlesme)agDataGrid1.FocusedDataRow;
                if (sz != null)
                {
                    SelectedID = sz.ID;
                    txtTutar.Text = sz.Tutar.ToString();
                    foreach (var item in AracListesi)
                    {
                        if (item.ID == sz.AracID)
                        {
                            txtArac.Text = item.Plaka;
                            txtSistemNo.Text = item.SistemNo;
                            txtSistemNo.Tag = item.SistemID;
                            AracBul(txtArac.Text);
                            break;
                        }
                    }

                    for (int i = 0; i < cmbFilm.Items.Count; i++)
                    {
                        Film flm = (Film)cmbFilm.Items[i];
                        if (flm.ID == sz.FilmID)
                            cmbFilm.SelectedIndex = i;
                    }
                    dteBaslangic.SelectedDate = sz.BaslangicTarihi;
                    dteBitis.SelectedDate = sz.BitisTarihi;
                }
            }
        }

        void SozlesmeTanitim_Loaded(object sender, RoutedEventArgs e)
        {
            SelectedID = -1;
            dteBaslangic.SelectedDate = DateTime.Now;
            dteBitis.SelectedDate = DateTime.Now;
            LoadAracTanimlari();

            switch (this.FormTipi)
            {
                case FormTipleri.FilmSozlesmesi:
                    this.Title = "Film Sözleşmeleri";
                    agDataGrid1.AddColumn("BaslangicTarihi");
                    agDataGrid1.AddColumn("BitisTarihi");
                    agDataGrid1.AddColumn("AracKodu");
                    agDataGrid1.AddColumn("Plaka");
                    agDataGrid1.AddColumn("FilmAdi");
                    agDataGrid1.AddColumn("Tutar");
                    break;
                case FormTipleri.GarantiSozlesmesi:
                    this.Title = "Garanti Sözleşmeleri";
                    grdLay.RowDefinitions[4].Height = new GridLength(0);
                    LayoutRoot.RowDefinitions[0].Height = new GridLength(70, GridUnitType.Star);
                    LayoutRoot.RowDefinitions[1].Height = new GridLength(30, GridUnitType.Star);
                    lblFilm.Visibility = System.Windows.Visibility.Collapsed;
                    cmbFilm.Visibility = System.Windows.Visibility.Collapsed;

                    agDataGrid1.AddColumn("BaslangicTarihi");
                    agDataGrid1.AddColumn("BitisTarihi");
                    agDataGrid1.AddColumn("AracKodu");
                    agDataGrid1.AddColumn("Plaka");
                    agDataGrid1.AddColumn("Tutar");
                    break;
                default:
                    break;
            }
        }


        private void LoadFilmTanimlari()
        {
            EntityQuery<Film> qry = context.GetFilmlerQuery().OrderBy(x => x.Adi);
            LoadOperation<Film> operation = context.Load(qry);
            operation.Completed += (ss, oo) =>
            {
                LoadOperation<Film> op = ss as LoadOperation<Film>;
                if (op.HasError)
                {
                    System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                    System.Windows.MessageBoxButton.OK);
                    op.MarkErrorAsHandled();
                }
                else
                {
                    FilmListesi.AddRange(op.Entities.Select(x => new Film { ID = x.ID, Adi = x.Adi }).ToArray());
                    cmbFilm.DisplayMemberPath = "Adi";
                    cmbFilm.ItemsSource = op.Entities;

                    LoadFilmSozlesmeleri();
                }
            };
        }
        private void LoadAracTanimlari()
        {
            EntityQuery<Arac> qry = context.GetAraclarQuery().OrderBy(x => x.Plaka);
            LoadOperation<Arac> operation = context.Load(qry);
            operation.Completed += (ss, oo) =>
            {
                LoadOperation<Arac> op = ss as LoadOperation<Arac>;
                if (op.HasError)
                {
                    System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                    System.Windows.MessageBoxButton.OK);
                    op.MarkErrorAsHandled();
                }
                else
                {
                    AracListesi.AddRange(op.Entities.Select(x => new Arac
                    {
                        ID = x.ID,
                        AracKodu = x.AracKodu,
                        AltCariKodu = x.AltCariKodu,
                        AnaCariKodu = x.AnaCariKodu,
                        FirmwareID = x.FirmwareID,
                        KoltukSayisi = x.KoltukSayisi,
                        MarkaID = x.MarkaID,
                        MontajTarihi = x.MontajTarihi,
                        MontajYeri = x.MontajYeri,
                        Plaka = x.Plaka,
                        SasiNo = x.SasiNo,
                        SistemID = x.SistemID,
                        SistemNo = x.SistemNo,
                        UretimYili = x.UretimYili
                    }).ToArray());
                }

                switch (this.FormTipi)
                {
                    case FormTipleri.FilmSozlesmesi:
                        LoadFilmTanimlari();
                        break;
                    case FormTipleri.GarantiSozlesmesi:
                        LoadGarantiSozlesmeleri();
                        break;
                }
            };
        }
        private void LoadFilmSozlesmeleri()
        {
            EntityQuery<FilmSozlesmesi> qry = context.GetFilmSozlesmeleriQuery();
            LoadOperation<FilmSozlesmesi> operation = context.Load(qry);
            operation.Completed += (ss, oo) =>
            {
                LoadOperation<FilmSozlesmesi> op = ss as LoadOperation<FilmSozlesmesi>;
                if (op.HasError)
                {
                    System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                    System.Windows.MessageBoxButton.OK);
                    op.MarkErrorAsHandled();
                }
                else
                {
                    List<FilmSozlesmesi> liste = op.Entities.Select(x => new FilmSozlesmesi { AracID = x.AracID, ID = x.ID, Tutar = x.Tutar, FilmID = x.FilmID, BaslangicTarihi = x.BaslangicTarihi, BitisTarihi = x.BitisTarihi }).ToList();
                    List<Sozlesme> sonuc = (from s in liste
                                            join a in AracListesi on s.AracID equals a.ID
                                            join f in FilmListesi on s.FilmID equals f.ID
                                            select new Sozlesme { ID = s.ID, BaslangicTarihi = s.BaslangicTarihi, BitisTarihi = s.BitisTarihi, AracKodu = a.AracKodu, Plaka = a.Plaka, FilmAdi = f.Adi, Tutar = s.Tutar, AracID = a.ID, FilmID = f.ID }).ToList();

                    agDataGrid1.DataSource = sonuc;
                }
            };
        }
        private void LoadGarantiSozlesmeleri()
        {
            EntityQuery<GarantiSozlesmesi> qry = context.GetGarantiSozlesmeleriQuery();
            LoadOperation<GarantiSozlesmesi> operation = context.Load(qry);
            operation.Completed += (ss, oo) =>
            {
                LoadOperation<GarantiSozlesmesi> op = ss as LoadOperation<GarantiSozlesmesi>;
                if (op.HasError)
                {
                    System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                    System.Windows.MessageBoxButton.OK);
                    op.MarkErrorAsHandled();
                }
                else
                {
                    List<GarantiSozlesmesi> liste = op.Entities.Select(x => new GarantiSozlesmesi { AracID = x.AracID, ID = x.ID, Tutar = x.Tutar, BaslangicTarihi = x.BaslangicTarihi, BitisTarihi = x.BitisTarihi }).ToList();
                    List<Sozlesme> sonuc = (from s in liste
                                            join a in AracListesi on s.AracID equals a.ID
                                            select new Sozlesme { ID = s.ID, BaslangicTarihi = s.BaslangicTarihi, BitisTarihi = s.BitisTarihi, AracKodu = a.AracKodu, Plaka = a.Plaka, Tutar = s.Tutar, AracID = a.ID, FilmID = -1 }).ToList();

                    agDataGrid1.DataSource = sonuc;
                }
            };
        }

        private void SaveFilmSozlesme()
        {
            if (!string.IsNullOrEmpty(txtSistemNo.Text) && cmbFilm.SelectedIndex > -1 && !string.IsNullOrEmpty(txtTutar.Text))
            {
                LoadOperation<FilmSozlesmesi> operation = context.Load(context.GetFilmSozlesmeleriQuery().Where(x => x.ID == SelectedID));
                operation.Completed += (ss, oo) =>
                {
                    LoadOperation<FilmSozlesmesi> op = ss as LoadOperation<FilmSozlesmesi>;
                    if (op.HasError)
                    {
                        System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                        System.Windows.MessageBoxButton.OK);
                        op.MarkErrorAsHandled();
                    }
                    else
                    {
                        SelectedID = -1;
                        FilmSozlesmesi oz = op.Entities.FirstOrDefault();
                        if (oz != null)
                        {
                            oz.AracID = Cevir.Parse<int>(txtSistemNo.Tag);
                            oz.BaslangicTarihi = dteBaslangic.SelectedDate.Value;
                            oz.BitisTarihi = dteBitis.SelectedDate.Value;
                            oz.FilmID = ((Film)cmbFilm.SelectedItem).ID;
                            oz.Tutar = Convert.ToDouble(txtTutar.Text);
                            context.SubmitChanges(so =>
                            {
                                if (so.HasError)
                                    MessageBox.Show("Hata:\r\n" + so.Error.Message);
                                else
                                {
                                    LoadFilmSozlesmeleri();
                                }
                            }, null);
                        }
                        else
                        {
                            FilmSozlesmesi newoz = new FilmSozlesmesi();
                            newoz.AracID = Cevir.Parse<int>(txtSistemNo.Tag);
                            newoz.BaslangicTarihi = dteBaslangic.SelectedDate.Value;
                            newoz.BitisTarihi = dteBitis.SelectedDate.Value;
                            newoz.FilmID = ((Film)cmbFilm.SelectedItem).ID;
                            newoz.Tutar = Convert.ToDouble(txtTutar.Text);

                            context.FilmSozlesmesis.Add(newoz);
                            context.SubmitChanges(so =>
                            {
                                if (so.HasError)
                                    MessageBox.Show("Hata:\r\n" + so.Error.Message);
                                else
                                {
                                    LoadFilmSozlesmeleri();
                                }
                            }, null);
                        }
                    }
                };
            }
        }
        private void SaveGarantiSozlesme()
        {
            if (!string.IsNullOrEmpty(txtSistemNo.Text) && !string.IsNullOrEmpty(txtTutar.Text))
            {
                LoadOperation<GarantiSozlesmesi> operation = context.Load(context.GetGarantiSozlesmeleriQuery().Where(x => x.ID == SelectedID));
                operation.Completed += (ss, oo) =>
                {
                    LoadOperation<GarantiSozlesmesi> op = ss as LoadOperation<GarantiSozlesmesi>;
                    if (op.HasError)
                    {
                        System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                        System.Windows.MessageBoxButton.OK);
                        op.MarkErrorAsHandled();
                    }
                    else
                    {
                        SelectedID = -1;
                        GarantiSozlesmesi oz = op.Entities.FirstOrDefault();
                        if (oz != null)
                        {
                            oz.AracID = Cevir.Parse<int>(txtSistemNo.Tag);
                            oz.BaslangicTarihi = dteBaslangic.SelectedDate.Value;
                            oz.BitisTarihi = dteBitis.SelectedDate.Value;
                            oz.Tutar = Convert.ToDouble(txtTutar.Text);
                            context.SubmitChanges(so =>
                            {
                                if (so.HasError)
                                    MessageBox.Show("Hata:\r\n" + so.Error.Message);
                                else
                                {
                                    LoadGarantiSozlesmeleri();
                                }
                            }, null);
                        }
                        else
                        {
                            GarantiSozlesmesi newoz = new GarantiSozlesmesi();
                            newoz.AracID = Cevir.Parse<int>(txtSistemNo.Tag);
                            newoz.BaslangicTarihi = dteBaslangic.SelectedDate.Value;
                            newoz.BitisTarihi = dteBitis.SelectedDate.Value;
                            newoz.Tutar = Convert.ToDouble(txtTutar.Text);

                            context.GarantiSozlesmesis.Add(newoz);
                            context.SubmitChanges(so =>
                            {
                                if (so.HasError)
                                    MessageBox.Show("Hata:\r\n" + so.Error.Message);
                                else
                                {
                                    txtSistemNo.Tag = 0;
                                    txtArac.Text = "";
                                    txtSistemNo.Text = "";
                                    txtTutar.Text = "";
                                    LoadGarantiSozlesmeleri();
                                }
                            }, null);
                        }
                    }
                };
            }
        }

        private void DeleteFilmSozlesmesi()
        {
            if (SelectedID > -1)
            {
                LoadOperation<FilmSozlesmesi> operation = context.Load(context.GetFilmSozlesmeleriQuery().Where(x => x.ID == SelectedID));
                operation.Completed += (ss, oo) =>
                {
                    LoadOperation<FilmSozlesmesi> op = ss as LoadOperation<FilmSozlesmesi>;
                    if (op.HasError)
                    {
                        System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                        System.Windows.MessageBoxButton.OK);
                        op.MarkErrorAsHandled();
                    }
                    else
                    {
                        SelectedID = -1;
                        FilmSozlesmesi oz = op.Entities.FirstOrDefault();
                        context.FilmSozlesmesis.Add(oz);
                        context.SubmitChanges(so =>
                        {
                            if (so.HasError)
                                MessageBox.Show("Hata:\r\n" + so.Error.Message);
                            else
                            {
                                LoadFilmSozlesmeleri();
                            }
                        }, null);
                    }
                };
            }
        }
        private void DeleteGarantiSozlesmesi()
        {
            if (SelectedID > -1)
            {
                LoadOperation<GarantiSozlesmesi> operation = context.Load(context.GetGarantiSozlesmeleriQuery().Where(x => x.ID == SelectedID));
                operation.Completed += (ss, oo) =>
                {
                    LoadOperation<GarantiSozlesmesi> op = ss as LoadOperation<GarantiSozlesmesi>;
                    if (op.HasError)
                    {
                        System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                        System.Windows.MessageBoxButton.OK);
                        op.MarkErrorAsHandled();
                    }
                    else
                    {
                        SelectedID = -1;
                        GarantiSozlesmesi oz = op.Entities.FirstOrDefault();
                        context.GarantiSozlesmesis.Remove(oz);
                        context.SubmitChanges(so =>
                        {
                            if (so.HasError)
                                MessageBox.Show("Hata:\r\n" + so.Error.Message);
                            else
                            {
                                LoadGarantiSozlesmeleri();
                            }
                        }, null);
                    }
                };
            }
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            switch (this.FormTipi)
            {
                case FormTipleri.FilmSozlesmesi:
                    SaveFilmSozlesme();
                    break;
                case FormTipleri.GarantiSozlesmesi:
                    SaveGarantiSozlesme();
                    break;
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            switch (this.FormTipi)
            {
                case FormTipleri.FilmSozlesmesi:
                    DeleteFilmSozlesmesi();
                    break;
                case FormTipleri.GarantiSozlesmesi:
                    DeleteGarantiSozlesmesi();
                    break;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            AracListesi liste = new AracListesi();
            liste.Filtre = txtArac.Text;
            liste.ListeTipi = Views.AracListesi.ListeTipleri.Arac;
            liste.Show();
            liste.Closed += (s, o) =>
            {
                AracListesi frm = (AracListesi)s;
                if (frm.DialogResult.HasValue && frm.DialogResult.Value)
                {
                    SecilenArac = frm.SecilenArac;
                    txtArac.Text = SecilenArac.Plaka;
                    foreach (var item in AracListesi)
                    {
                        if (item.Plaka == SecilenArac.Plaka)
                        {
                            txtSistemNo.Text = item.SistemNo;
                            txtSistemNo.Tag = SecilenArac.ID;
                            break;
                        }
                    }
                }
            };
        }

        private void btnAracAc_Click(object sender, RoutedEventArgs e)
        {
            if (SecilenArac != null)
            {
                BilgiEkrani frm = new BilgiEkrani();
                AracBilgi yeni = SecilenArac;
                frm.AracKodu = yeni.AracKodu;
                frm.FirmaAdi = yeni.FirmaAdi;
                frm.GrupAdi = yeni.GrupAdi;
                frm.Adres = yeni.Adres;
                frm.Show();
            }
        }

        private void AracBul(string plaka)
        {
            EntityQuery<AracBilgi> qry = context.GetAracBilgileriQuery().Where(x => x.Plaka.StartsWith(plaka));
            LoadOperation<AracBilgi> operation = context.Load(qry);
            operation.Completed += (ss, oo) =>
            {
                LoadOperation<AracBilgi> op = ss as LoadOperation<AracBilgi>;
                if (op.HasError)
                {
                    System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                    System.Windows.MessageBoxButton.OK);
                    op.MarkErrorAsHandled();
                }
                else
                {
                    AracBilgi arac = op.Entities.FirstOrDefault();
                    if (arac != null)
                    {
                        SecilenArac = arac;
                        txtArac.Text = arac.Plaka;

                        foreach (var item in AracListesi)
                        {
                            if (item.Plaka == arac.Plaka)
                            {
                                txtSistemNo.Text = item.SistemNo;
                                txtSistemNo.Tag = SecilenArac.ID;
                                break;
                            }
                        }

                    }
                }
            };
        }

        private void txtArac_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                AracBul(txtArac.Text);
            }
        }
    }
}

